<script setup>
import { onMounted, onUnmounted, ref, watch } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import henanGeoJson from '@/assets/河南省.json'
import { spotsInfoStore } from "@/stores/spots";
import { getCityData, getSpotsFood, getSpotsHouse } from "@/api/apitest";
import FoodView from "./FuncFoodHouse/FoodView.vue";
import HouseView from "./FuncFoodHouse/HouseView.vue";
import FoodListView from "./FuncFoodHouse/FoodListView.vue";
import HouseListView from "./FuncFoodHouse/HouseListView.vue";
import { DriversInfoStore } from "@/stores/driver";


// let Data = []
let markers = []
const spotsStore = spotsInfoStore()
const driversStore = DriversInfoStore()
let map = null;
let polygons = new Map()

let classifytype = new Map()
const geoJsonData = { ...henanGeoJson }

let foodmarkers = []
let housemarkers = []

let circle = null;//框圈
// console.log(geoJsonData);

//获取城市景点数据
async function getCitySpotsData(cityname) {
  const data = await getCityData(cityname)
  spotsStore.SetcityData(data.data)
  spotsStore.SettempData(data.data)
  localStorage.setItem('cityData', JSON.stringify(cityname))
  // console.log(spotsStore.cityData, 'cityData');
  // console.log(data)
}
//景点分类
const classifyPlcaes = (data) => {
  classifytype.clear()//清空数据
  for (let i = 0; i < data.length; i++) {
    // 数组去重
    let temp = [...new Set(data[i].type.split(/[;|]/))];
    // console.log(temp);

    //景点分类计算
    for (let j = 0; j < temp.length; j++) {
      if (classifytype.has(temp[j])) {
        classifytype.set(temp[j], classifytype.get(temp[j]) + 1)
      } else {
        classifytype.set(temp[j], 1)
      }
    }
  }
  spotsStore.Setspot(new Map(classifytype)) // 确保在数据更新后调用
}
//添加marker标记点
const addMarker = (data) => {
  map.getAllOverlays('marker').forEach(marker => {
    map.remove(marker);
  });
  map.getAllOverlays('circle').forEach(circle => {
    map.remove(circle);
  });
  markers = []
  for (let i = 0; i < data.length; i++) {
    markers[i] = new AMap.Marker({
      position: data[i].location,
      title: data[i].spotname,
      // extData: data[i],
    });
    markers[i].on('click', (e) => {
      if (spotsStore.FuncFoodOn) {
        getSpotsFoodHouse(data[i], Number(spotsStore.Radius))
      }
      if (spotsStore.FuncHouseOn) {
        getSpotsHouseData(data[i], Number(spotsStore.HouseRadius))
      }
      if (driversStore.FuncCarDriver) {
        driversStore.SetSelectPoint(data[i])
        driversStore.SetCarOpen(true)
      }
      let content = `
      <div style="width: 200px; height: 100px; font-size:14px;  "  >
        <h3>${data[i].spotname}</h3>
        <p>地址：${data[i].address}</p>
        <p>电话：${data[i].tel || '暂无信息'}</p>
      </div>
      `
      let infoWindow = new AMap.InfoWindow({
        // isCustom: true, //使用自定义窗体
        content: content,
        // offset: new AMap.Pixel(10, -10),
        anchor: "bottom-right",
      });
      infoWindow.open(map, e.target.getPosition());
      //根据覆盖物范围调整视野
      map.setFitView([markers[i]])
    })
    map.add(markers[i]);
  }
}
//添加foodmarker标记点
const addFoodMarker = (data) => {
  if (foodmarkers.length > 0) {
    foodmarkers.map(e => {
      // console.log(e);
      map.remove(e)
    })
  }
  foodmarkers = []
  // 创建一个 Icon
  let startIcon = new AMap.Icon({
    // 图标尺寸
    size: new AMap.Size(34, 34),
    // 图标的取图地址
    image: 'http://localhost:3000/uploads\\1742194055218-food.png',
    // 图标所用图片大小
    imageSize: new AMap.Size(50, 50),
    // 图标取图偏移量
    imageOffset: new AMap.Pixel(-8, -8)
  });
  for (let i = 0; i < data.length; i++) {
    foodmarkers[i] = new AMap.Marker({
      position: data[i].location.split(','),
      title: data[i].name,
      icon: startIcon,
      // extData: data[i],
    });
    foodmarkers[i].on('click', (e) => {
      // console.log(markers[i].extData);
      if (driversStore.FuncCarDriver) {
        driversStore.SetSelectPoint(data[i])
        driversStore.SetCarOpen(true)
      }
      let content = `
      <div style="width: 200px; height: 100px; font-size:14px;  "  >
        <h3>${data[i].name}</h3>
        <p>地址：${data[i].address}</p>
      </div>
      `

      let infoWindow = new AMap.InfoWindow({
        // isCustom: true, //使用自定义窗体
        content: content,
        // offset: new AMap.Pixel(10, -10),
        anchor: "bottom-right",
      });
      infoWindow.open(map, e.target.getPosition());
      //详细信息侧边弹窗
      spotsStore.SetFoodOpen(true)
      spotsStore.SetSelectedFood(data[i])
    })
    map.add(foodmarkers[i]);
    // console.log(foodmarkers[i], 'foodmarkers');
  }
}
// //添加housemarker标记点
const addHouseMarKer = (data) => {
  if (housemarkers.length > 0) {
    housemarkers.map(e => {
      // console.log(e);
      map.remove(e)
    })
  }
  housemarkers = []
  // 创建一个 Icon
  let startIcon = new AMap.Icon({
    // 图标尺寸
    size: new AMap.Size(34, 34),
    // 图标的取图地址
    image: 'http://localhost:3000/uploads\\1742194097548-house.jpg',
    // 图标所用图片大小
    imageSize: new AMap.Size(54, 54),
    // 图标取图偏移量
    imageOffset: new AMap.Pixel(-11, -10)
  });
  for (let i = 0; i < data.length; i++) {
    housemarkers[i] = new AMap.Marker({
      position: data[i].location.split(','),
      title: data[i].name,
      icon: startIcon,
      // extData: data[i],
    });
    housemarkers[i].on('click', (e) => {
      // console.log(markers[i].extData);
      if (driversStore.FuncCarDriver) {
        driversStore.SetSelectPoint(data[i])
        driversStore.SetCarOpen(true)
      }
      let content = `
      <div style="width: 200px; height: 100px; font-size:14px;  "  >
        <h3>${data[i].name}</h3>
        <p>地址：${data[i].address}</p>
        <p>电话：${data[i].business.tel || '暂无信息'}</p>
      </div>
      `

      let infoWindow = new AMap.InfoWindow({
        // isCustom: true, //使用自定义窗体
        content: content,
        // offset: new AMap.Pixel(10, -10),
        anchor: "bottom-right",
      });
      infoWindow.open(map, e.target.getPosition());
      //详细信息侧边弹窗
      spotsStore.SetHouseOpen(true)
      spotsStore.SetSelectedHouse(data[i])
    })
    map.add(housemarkers[i]);
    // console.log(foodmarkers[i], 'foodmarkers');
  }
}
//获取景点附近美食数据
const getSpotsFoodHouse = async (data, radius = 300) => {
  const location = `${data.location[0]},${data.location[1]}`
  circle = new AMap.Circle({
    center: new AMap.LngLat(data.location[0], data.location[1]), //圆心
    radius: radius, //半径
    borderWeight: 2, //描边的宽度
    strokeColor: "blue", //轮廓线颜色
    strokeOpacity: 0.5, //轮廓线透明度
    strokeWeight: 2, //轮廓线宽度
    fillOpacity: 0, //圆形填充透明度
    strokeStyle: "solid", //轮廓线样式
    // zIndex: 50, //圆形的叠加顺序
  })
  map.getAllOverlays('circle').forEach(circle => {
    map.remove(circle);
  });
  map.add(circle)
  map.setFitView([circle])
  // console.log(circle, typeof radius, typeof Number(spotsStore.Radius));
  // const res = await getSpotsFood(location, radius, types)
  const res = await getSpotsFood(location, radius)
  // console.log(location, res.pois);
  spotsStore.SetFoodData(res.pois)
  addFoodMarker(spotsStore.FoodData)
}
//获取景点附近住宿数据
const getSpotsHouseData = async (data, radius = 300) => {
  const location = `${data.location[0]},${data.location[1]}`
  circle = new AMap.Circle({
    center: new AMap.LngLat(data.location[0], data.location[1]), //圆心
    radius: radius, //半径
    borderWeight: 2, //描边的宽度
    strokeColor: "green", //轮廓线颜色
    strokeOpacity: 0.5, //轮廓线透明度
    strokeWeight: 2, //轮廓线宽度
    fillOpacity: 0, //圆形填充透明度
    strokeStyle: "solid", //轮廓线样式
    // zIndex: 50, //圆形的叠加顺序
  })
  map.getAllOverlays('circle').forEach(circle => {
    map.remove(circle);
  });
  map.add(circle)
  //根据覆盖物范围调整视野
  map.setFitView([circle])
  // console.log(circle, typeof radius, typeof Number(spotsStore.Radius));
  const res = await getSpotsHouse(location, radius)
  // console.log(location, res.pois);
  spotsStore.SetHouseData(res.pois)
  addHouseMarKer(spotsStore.HouseData)
}
onMounted(() => {
  AMapLoader.load({
    key: "525d19eaad172b7619b29b5138a297db", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    // AMapUI: {
    //   version: '1.1',
    //   plugins: ['overlay/SimpleMarker']
    // },
    // plugins: ["AMap.DistrictLayer"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap) => {
      map = new AMap.Map("container", {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 7, // 初始化地图级别
        center: [113.3008, 33.7352], // 初始化地图中心点位置
      });
      //河南省geo
      let Geo = new AMap.plugin("AMap.GeoJSON", function () {
        //创建 geoJSON 实例，传入 GeoJSON 数据和其他选项
        let geoJson = new AMap.GeoJSON({
          //将字符串形式的 GeoJSON 数据解析为对象
          geoJSON: geoJsonData,
          //定义一个回调函数来创建多边形对象，该函数接收一个 geojson 对象和一个 lnglats 数组作为参数
          getPolygon: function (geojson, lnglats) {
            // 返回一个新的 AMap.Polygon 对象，传入路径、填充透明度、边框颜色和填充颜色等选项
            //还可以自定义 getMarker 和 getPolyline，用于创建标记和折线对象
            // console.log(geojson.properties.name);

            let polygon = new AMap.Polygon({
              path: lnglats,
              fillOpacity: 0.3,
              strokeColor: "black",
              strokeOpacity: 0.9,
              strokeStyle: "dashed",
              strokeWeight: 2,
              fillColor: "white",
            });
            // console.log('polygon', polygon);
            // // polygon.on('click', alert('11111'))
            polygons.set(geojson.properties.name, polygon)
            return polygon
          },
        });
        map.add(geoJson);//将geoJson对象添加到地图上
      });
      //高亮显示选择城市和cityname
      for (const temp of polygons) {
        // console.log(temp[0]);
        //hover
        const gaoguang = (e) => {
          infoWindow.open(map, e.lnglat);
          temp[1].setOptions({
            fillColor: 'yellow',
            fillOpacity: 0.8,
          })
        }
        const cleargaoguang = () => {
          infoWindow.close()
          temp[1].setOptions({
            fillColor: 'white',
            fillOpacity: 0,
          })
        }
        //实例化信息窗体
        let content = `${temp[0]}`

        let infoWindow = new AMap.InfoWindow({
          isCustom: true, //使用自定义窗体
          content: content,
          offset: new AMap.Pixel(10, -10),
          // anchor: "bottom-right",
        });

        temp[1].on('mouseover', gaoguang);

        temp[1].on('mouseout', cleargaoguang)
        temp[1].on('rightclick', () => {
          temp[1].on('mouseover', gaoguang);
        })
        temp[1].on('click', (e) => {
          // spotsStore.showclassify = true
          temp[1].off('mouseover', gaoguang)

          temp[1].setOptions({
            fillColor: 'white',
            fillOpacity: 0,
          })
          spotsStore.Setcityname(temp[0])
          map.setCity(temp[0]);
          // GetInfo(temp[0])
          getCitySpotsData(temp[0])
          classifyPlcaes(spotsStore.cityData)
          addMarker(spotsStore.cityData)
        })
      }

      //遮罩
      let ZheZhao = new AMap.plugin("AMap.DistrictSearch", function () {
        new AMap.DistrictSearch({
          extensions: 'all',
          subdistrict: 0
        }).search('河南省', function (status, result) {
          // 外多边形坐标数组和内多边形坐标数组
          let outer = [
            new AMap.LngLat(-360, 90, true),
            new AMap.LngLat(-360, -90, true),
            new AMap.LngLat(360, -90, true),
            new AMap.LngLat(360, 90, true),
          ];
          let holes = result.districtList[0].boundaries

          let pathArray = [
            outer
          ];
          pathArray.push.apply(pathArray, holes)
          let polygon = new AMap.Polygon({
            strokeColor: 'black',
            strokeWeight: 2,
            fillColor: '#71B3ff',
            fillOpacity: 0.9
          });
          polygon.setPath(pathArray);
          map.add(polygon)
        })
      });

    })
    .catch((e) => {
      console.log(e);
    });
});

watch(() => spotsStore.cityData, (newCityData) => {
  classifyPlcaes(newCityData);
  addMarker(newCityData)
  // console.log(newCityData, 'spotsStore.cityData');
}, { deep: true });
//鼠标点击选中地点信息
watch(() => spotsStore.selectedSpot, (newSelectedSpot) => {
  if (spotsStore.FuncFoodOn) {
    getSpotsFoodHouse(newSelectedSpot, Number(spotsStore.Radius))
  }
  if (spotsStore.FuncHouseOn) {
    getSpotsHouseData(newSelectedSpot, Number(spotsStore.HouseRadius))
    // console.log('3131313');
  }
  if (newSelectedSpot) {
    const marker = markers.find(marker => marker.getTitle() === newSelectedSpot.name);
    if (marker) {
      const content = `
      <div style="width: 200px; height: 100px; font-size:14px;  "  >
        <h3>${newSelectedSpot.name}</h3>
        <p>地址：${newSelectedSpot.address}</p>
        <p>电话：${newSelectedSpot.tel || '暂无信息'}</p>
      </div>
      `;
      const infoWindow = new AMap.InfoWindow({
        content: content,
        anchor: "bottom-right",
      });
      infoWindow.open(map, marker.getPosition());
      //根据覆盖物范围调整视野
      map.setFitView([marker])
    }
  }
  // console.log('havegetspot');

}, { deep: true });
//选中美食地点
watch(() => spotsStore.TableFood, (newTableFood) => {
  if (newTableFood) {
    const marker = foodmarkers.find(marker => marker.getTitle() === newTableFood.name);
    if (marker) {
      const content = `
      <div style="width: 200px; height: 100px; font-size:14px;  "  >
        <h3>${newTableFood.name}</h3>
        <p>地址：${newTableFood.address}</p>
      </div>
      `;
      const infoWindow = new AMap.InfoWindow({
        content: content,
        anchor: "bottom-right",
      });
      infoWindow.open(map, marker.getPosition());
      //根据覆盖物范围调整视野
      map.setFitView([marker])
    }
  }
}, { deep: true })
//选中住房地点
watch(() => spotsStore.TableHouse, (newTableHouse) => {
  if (newTableHouse) {
    const marker = housemarkers.find(marker => marker.getTitle() === newTableHouse.name);
    if (marker) {
      const content = `
      <div style="width: 200px; height: 100px; font-size:14px;  "  >
        <h3>${newTableHouse.name}</h3>
        <p>地址：${newTableHouse.address}</p>
      </div>
      `;
      const infoWindow = new AMap.InfoWindow({
        content: content,
        anchor: "bottom-right",
      });
      infoWindow.open(map, marker.getPosition());
      //根据覆盖物范围调整视野
      map.setFitView([marker])
    }
  }
}, { deep: true })
onUnmounted(() => {
  map?.destroy();
});
</script>

<template>
  <div id="container">

  </div>
  <div id="FoodList" v-if="spotsStore.FuncFoodOn">
    <FoodListView />
  </div>
  <div id="HouseList" v-if="spotsStore.FuncHouseOn">
    <HouseListView />
  </div>
  <div v-if="spotsStore.FuncFoodOn">
    <FoodView />
  </div>
  <div v-if="spotsStore.FuncHouseOn">
    <HouseView />
  </div>
</template>

<style lang="scss" scoped>
#container {
  width: 100%;
  height: 800px;
}

#FoodList {
  position: absolute;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 9%;
  right: 17%;
  width: 300px;
  height: 300px;
  border-radius: 5%;
  opacity: 80%;
}

#HouseList {
  position: absolute;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 9%;
  left: 22%;
  width: 300px;
  height: 300px;
  border-radius: 5%;
  opacity: 80%;
}
</style>
